package org.whatever.aha.zjut.platform.message_topic;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.constant.MsgRedisConstant;
import org.whatever.aha.zjut.base.exception.AppException;

/**
 * @author Baby_mo
 */
@Service
@RequiredArgsConstructor
public class TopicService {
    final RedisTemplate<String, Object> redisTemplate;
    final MsgRedisConstant msgRedisConstant;

    /**
     * TODO 确定topic种类，改为传入topicId
     * 订阅topic
     */
    public void subscribe(int userId, String topic) {
        String key = msgRedisConstant.getKeyUserTopicSet(userId);
        long add = redisTemplate.opsForSet().add(key, topic);
        if (add < 1) {
            throw new AppException(ErrorCode.FAIL_TO_SUBSCRIBE, "订阅失败");
        }
    }

    /**
     * 取消订阅
     */
    public void unsubscribe(int userId, String topic) {
        String key = msgRedisConstant.getKeyUserTopicSet(userId);
        redisTemplate.opsForSet().remove(key, topic);
    }
}
